﻿using System;
using System.Collections.Generic;

namespace ConsoleApp.拦截器
{
    public abstract class BaseOrderInterceptHandler: IOrderInterceptHandler
    {
        public IEnumerable<OrderInterceptOutput> InterceptOrders(IEnumerable<OrderInterceptInput> inputs,
            OrderInterceptContextFactory factory)
        {
            if (inputs == null) throw new ArgumentNullException(nameof(inputs));
            if (factory == null) throw new ArgumentNullException(nameof(factory));

            var businessChain = BuidOrderInterceptorBusinessChain();
            foreach (var input in inputs)
            {
                var orderInterceptContext = factory.CreateContext(input);
                businessChain.Run(orderInterceptContext);
                if (orderInterceptContext.Output!=null)
                {
                    yield return orderInterceptContext.Output;
                }
            }

        }

        public abstract IEnumerable<IBusinessPlugin<OrderInterceptContext>> GetOrderInterceptPlugins();

        private OrderInterceptBusinessChain BuidOrderInterceptorBusinessChain()
        {
            var filters= GetOrderInterceptPlugins();
            var builder= new BusinessChainBuilder<OrderInterceptBusinessChain, OrderInterceptContext>();
            foreach (var filter in filters)
            {
                builder.UsePlugin(filter);
            }
            return builder.Build();
        }
    }
}